package com.tansun.easycare.rule.approval.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tansun.easycare.modules.sys.utils.UserUtils;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.task.Comment;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.core.web.BaseController;
import com.tansun.easycare.rule.approval.entity.RuleManageInfo;
import com.tansun.easycare.rule.approval.entity.RulePublishApproval;
import com.tansun.easycare.rule.approval.entity.RuleTaskBean;
import com.tansun.easycare.rule.approval.service.RulePublishApprovalService;
import com.tansun.easycare.rule.codeblock.entity.RuleCodeblock;
import com.tansun.easycare.rule.codeblock.entity.RuleCodeblockInfo;
import com.tansun.easycare.rule.codeblock.service.RuleCodeblockService;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.common.model.SelectEditorVo;
import com.tansun.easycare.rule.datasource.service.RuleDatasourceService;
import com.tansun.easycare.rule.deployonline.model.RuleDeployVO;
import com.tansun.easycare.rule.deployonline.service.RuleDeployOnlineService;
import com.tansun.easycare.rule.front.entity.RuleDatasource;
import com.tansun.easycare.rule.ruleflow.service.RuleFlowService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.wf.activiti.constants.WorkflowConstants;
import com.tansun.workflow.model.ButtonModel;
import com.tansun.workflow.model.ProcessBean;
import com.tansun.workflow.model.ProcessInfo;
import com.tansun.workflow.model.TaskBean;
import com.tansun.workflow.model.TaskInfo;
import com.tansun.workflow.service.WorkFlowClientService;

/**
 * 单表生成Controller
 * @author @
 * @version 2019-11-20
 */
@RestController
@RequestMapping(value = "/approval/rulePublishApproval")
public class RulePublishApprovalController extends BaseController {
	
	@Autowired
	private RulePublishApprovalService rulePublishApprovalService;

	@Autowired
	private WorkFlowClientService workFlowClientService;

	@Autowired
	private TaskService taskService;

	@Autowired
	private HistoryService historyService;

	@Autowired
	private RuleManageService ruleManageService;
	@Autowired
	private RuleCodeblockService ruleCodeblockService;
	@Autowired
	private RuleFlowService ruleFlowService;
	@Autowired
	private RuleDeployOnlineService ruleDeployOnlineService;
	@Autowired
	private RuleDatasourceService datasourceService;

    @RequestMapping("unpublicList")
    public ResponseVO unpublicList(@RequestBody RulePublishApproval rulePublishApproval) throws Exception {
    	List<RuleManageInfo> rlist = new ArrayList<RuleManageInfo>();
		if (StringUtils.isNotBlank(rulePublishApproval.getId())){
			rulePublishApproval = rulePublishApprovalService.get(rulePublishApproval.getId());
			String details = rulePublishApproval.getRuleUpdateDetail();
			rlist = JSON.parseArray(details,RuleManageInfo.class);
		}
		if (rlist.size()==0){
			rlist = this.unPublishRules(rulePublishApproval.getProjectCode());
		}
        PageInfo<RuleManageInfo>  pageInfo = new PageInfo<RuleManageInfo>();
        pageInfo.setList(rlist);
        ResponseTable<RuleManageInfo>  resVo  = new  ResponseTable<RuleManageInfo>(pageInfo);  
        return resVo;
    }
    
	@RequestMapping(value = {"list", ""})
	public PageInfo<RulePublishApproval> list(RulePublishApproval rulePublishApproval, HttpServletRequest request, HttpServletResponse response, Model model) {
		PageInfo<RulePublishApproval> page = rulePublishApprovalService.findPage(new Page<RulePublishApproval>(), rulePublishApproval); 
		return page;
	}

	@RequestMapping(value = "form")
	public Map form(RulePublishApproval rulePublishApproval , String taskId, String flag, String projectCode) throws Exception {
		Map model = new HashMap();
		//flag c:已办，p:待办，a:申请
		flag = flag == null ? "a" : flag;
		if (StringUtils.isNotBlank(taskId)) {
			setTaskInfoToModel(model, taskId, flag,projectCode);
		}
		model.put("flag", flag);
		model.put("rulePublishApproval", rulePublishApproval);

		setRulsToModel(rulePublishApproval, model, flag, projectCode);
		model.put("projectCode", projectCode);
		//区分联机部署信息 ljt
		if(!flag.equals("a")){
			RulePublishApproval resultRulePublish = rulePublishApprovalService.get(rulePublishApproval.getId());
			String ruleUpdateDetail = resultRulePublish.getRuleUpdateDetail();
			List<RuleManageInfo> info = JSON.parseArray(ruleUpdateDetail, RuleManageInfo.class);
			if(info!=null&&info.get(0).getCode().equals("deployment")){
				RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
				ruleVersioninfo.setProjectCode(projectCode);
				ruleVersioninfo.setModelType(RuleModelTypeEnum.StrategyFlow.code);
				List<SelectEditorVo> list = this.ruleFlowService.getAllPublishVersion(ruleVersioninfo);
				model.put("list", list);
				String deploymentId = info.get(0).getId();
				RuleDeployVO ruleDeployVO = this.ruleDeployOnlineService.findRuleDeploy(deploymentId);
				model.put("vo", ruleDeployVO);
				model.put("operType", "dispaly");
				model.put("datasources", datasourceService.findList(new RuleDatasource()));
				return model;
			}
		}
		return model;
	}

	private void setRulsToModel(RulePublishApproval rulePublishApproval, Map model, String flag, String projectCode) throws Exception {
		if("a".equals(flag)){
			model.put("unPublishRules", this.unPublishRules(projectCode));

		}else{
			String details = rulePublishApproval.getRuleUpdateDetail();

			model.put("unPublishRules", JSON.parseArray(details,RuleManageInfo.class));
		}
	}

	@SuppressWarnings({ "deprecation", "rawtypes" })
	private void setTaskInfoToModel(Map model, String taskId, String flag, String projectCode) {
		org.activiti.engine.task.TaskInfo task = null;
		HistoricProcessInstance hiProc = null;
		if("p".equals(flag)){
			task = taskService.createTaskQuery().taskId(taskId).singleResult();
		}else{
			task = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
			List<Comment> taskComments = taskService.getTaskComments(taskId);
			if (CollectionUtils.isNotEmpty(taskComments)){
				model.put("comment", taskComments.get(0).getFullMessage());
			}

		}
		if (task == null) {
			return;
		}else {

            historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        }
		model.put("pEnd", hiProc == null ?"N":"Y");

		TaskInfo buttonInfo = new TaskInfo();
		buttonInfo.setActivityId(task.getTaskDefinitionKey());
		buttonInfo.setProcessDefineId(task.getProcessDefinitionId());
		TaskBean buttonBean = workFlowClientService.findButtonPower(buttonInfo);
		List<ButtonModel> buttonList = buttonBean.getActButtonModel();
		ProcessInfo info = new ProcessInfo();
		info.setProcessInstanceId(task.getProcessInstanceId());
		try {
			TaskBean taskBean = workFlowClientService.queryProcessTrack(info);
			List<Map> taskList = taskBean.getTaskList();
			model.put("hiTasks",taskList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("processInstanceId",task.getProcessInstanceId());
		model.put("taskId",taskId);
		model.put("projectCode",projectCode);
		model.put("btns",buttonList);
	}

	@RequestMapping(value = "save")
	public String save(RulePublishApproval rulePublishApproval, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception {
//		String taskId = request.getParameter("taskId");
//		String flag = request.getParameter("flag");
//		String projectCode = request.getParameter("projectCode");
//		if (!beanValidator(model, rulePublishApproval)) {
//			return form(rulePublishApproval, model,taskId,flag,projectCode);
//		}
//
//
//		if (StringUtils.isNotBlank(rulePublishApproval.getProcessInstancesId())) {
//			//已发起,修改表单内容
//			rulePublishApprovalService.save(rulePublishApproval);
//		} else {
//			//新发起流程
//			String id = UUID.randomUUID().toString();
//			rulePublishApproval.setId(id);
//
//
//			ProcessInfo processInfo = new ProcessInfo();
//			processInfo.setProcessDefineKey("rulepublish");
//			processInfo.setBusinessKey(id);
//			HashMap<String, String> taskExpandData = new HashMap<>();
//			taskExpandData.put("projectCode", projectCode);
//			processInfo.setTaskExpandData(taskExpandData);
//			processInfo.setUserId(UserUtils.getUser().getLoginName());
//			ProcessBean processBean = workFlowClientService.startProcess(processInfo);
//			if (WorkflowConstants.FAILED.equals(processBean.getRetCode())) {
//				throw new RuntimeException(processBean.getRetMsg());
//			}
//			String processInstanceId = processBean.getProcessInstanceId();
//			rulePublishApproval.setProcessInstancesId(processInstanceId);
//			rulePublishApproval.setIsNewRecord(true);
//			rulePublishApprovalService.save(rulePublishApproval);
//		}
//
//		setTaskInfoToModel(model, taskId, flag, projectCode);
//		setRulsToModel(rulePublishApproval, model, flag, projectCode);
//		model.put("procInstId", rulePublishApproval.getProcessInstancesId());
//		model.put("taskId", taskId);
//		model.put("flag", flag);
//		model.put("projectCode", projectCode);
//		addMessage(redirectAttributes, "保存单表成功");

		return "rule/approval/rulePublishApprovalForm";
//		return "redirect:"+Global.getAdminPath()+"/approval/rulePublishApproval/?repage";
	}
	@Transactional
	@RequestMapping(value = "delete")
	public String delete(RulePublishApproval rulePublishApproval, RedirectAttributes redirectAttributes) {
		rulePublishApprovalService.delete(rulePublishApproval);
		addMessage(redirectAttributes, "删除单表成功");
		return "redirect:"+"/approval/rulePublishApproval/?repage";
	}


//	@RequestMapping(value = "submitFirst")
//	@ResponseBody
//	public TaskBean submitFirst(String procInstId) throws Exception {
//		TaskBean taskBean = workFlowClientService.getTasksByProcessInstanceId(procInstId);
//		List<Map> taskList = taskBean.getTaskList();
//		String taskId = MapUtils.getString(taskList.get(0), "taskId");
//		TaskBean taskParams = new TaskBean();
//		taskParams.setTaskId(taskId);
//		taskParams.setUserId(UserUtils.getUser().getLoginName());
//		return workFlowClientService.submitTask(taskParams);
//	}

	@Transactional
	@RequestMapping(value = "submitFirst")
	public ResponseVO submitFirst(@RequestBody ProcessInfo processInfo) throws Exception {
		
		ResponseVO response = new ResponseVO();
		//新发起流程
		RulePublishApproval rulePublishApproval = new RulePublishApproval();
		String id = UUID.randomUUID().toString();
		rulePublishApproval.setId(id);
		rulePublishApproval.setRuleUpdateDetail(processInfo.getModelId());


		processInfo.setProcessDefineKey("rulepublish");
		processInfo.setBusinessKey(id);
		HashMap<String, String> taskExpandData = new HashMap<>();
		taskExpandData.put("projectCode", processInfo.getModelKey());
		processInfo.setTaskExpandData(taskExpandData);
		processInfo.setUserId(UserUtils.getSysService().getCurrUser().getId());
		ProcessBean processBean = workFlowClientService.startAndSubmitProcess(processInfo);
		response.setData(processBean);
		if (WorkflowConstants.FAILED.equals(processBean.getRetCode())) {
			response.setStatus(ResponseVO.ERROR);
		}
		String processInstanceId = processBean.getProcessInstanceId();
		rulePublishApproval.setProcessInstancesId(processInstanceId);
		rulePublishApproval.setIsNewRecord(true);
		rulePublishApprovalService.save(rulePublishApproval);
		response.setStatus(ResponseVO.OK);
		return response;
	}


	@RequestMapping(value = "submit")
	@ResponseBody
	@Transactional
	public ResponseVO submit(@RequestBody RuleTaskBean params ) throws Exception {
		TaskBean result = workFlowClientService.submitTask(params);
		RulePublishApproval entity = rulePublishApprovalService.get(params.getBusinessKey());
		entity.setRuleApprovalResult(params.getRuleApprovalResult());
		rulePublishApprovalService.save(entity);
		ResponseVO response = new ResponseVO();
		response.setStatus(WorkflowConstants.FAILED.equals(result.getRetCode()) ? ResponseVO.ERROR:ResponseVO.OK);
		response.setData(result);
		response.setDescription(result.getRetMsg());
		return response;
	}



	@RequestMapping(value = "unPublishRules")
	@ResponseBody
	public List<RuleManageInfo> unPublishRules(String projectCode) throws Exception {

		RuleManage r = new RuleManage();
		r.setProjectCode(projectCode);
		r.setActiveFlag("0");//过滤有效版本
		Page<RuleManage> page = new Page<>();
		page.setPageSize(Integer.MAX_VALUE);
		//page.setPageNo(1);
		r.setPage(page);
		List<RuleManage> list = ruleManageService.findMainManageList(r);
		//查询出待审批的函数变量(有更改过的)20200205 ljt
		RuleCodeblock condition = new RuleCodeblock();
		condition.setProjectCode(projectCode);
		List<RuleCodeblockInfo> arvalFuncParamList = ruleCodeblockService.findArvalFuncParamList(condition);
		List<RuleManageInfo> newList = new ArrayList<>();
		if (list != null) {
			for (RuleManage ruleManage : list) {
				RuleManageInfo ruleManageInfo = new RuleManageInfo();
				BeanUtils.copyProperties(ruleManage, ruleManageInfo);
				newList.add(ruleManageInfo);
			}
		}
		if(arvalFuncParamList!=null){
			for(RuleCodeblockInfo ruleCodeblock :arvalFuncParamList){
				RuleManageInfo ruleManageInfo = new RuleManageInfo();
				ruleManageInfo.setId(ruleCodeblock.getId());
				ruleManageInfo.setModelType("99");//99代表函数变量
				ruleManageInfo.setCode(ruleCodeblock.getFuncImport());
				ruleManageInfo.setName(ruleCodeblock.getFuncparamName());
				ruleManageInfo.setActiveVersion("v0.01");
				ruleManageInfo.setVersion("v1.00");
				ruleManageInfo.setUpdateDate(ruleCodeblock.getUpdateDate());
				ruleManageInfo.setUsers(ruleCodeblock.getUsers());
				newList.add(ruleManageInfo);
			}
		}
		return newList;

	}



}